﻿using Mono.Cecil.Cil;
using Project;
using System.Collections.Generic;
using UnityEngine;
using static UnityEditor.Progress;

public class PlayerWeapon : MonoBehaviour
{
    public int currentIndex = 1;
    public List<BaseWeapon> weaponList = new List<BaseWeapon>();
    private bool isMouseDown;

    private void Awake()
    {
        Init();
        EventCenter.GetInstance().AddEventListener<WeaponEnum>("AddWeapon", OnAddWeapon);
    }
    void Start()
    {
      
    }
    //响应添加武器事件
    private void OnAddWeapon(WeaponEnum type)
    {
        var info = WeaponDataSingle.Intacne.GetWeapomInfo(type);
        GameObject go = Instantiate(info.Prefab, transform);
        go.transform.localPosition = Vector3.zero;
        weaponList.Add(go.GetComponent<BaseWeapon>());
        go.SetActive(false);
    }
    private void OnDestroy()
    {
        EventCenter.GetInstance().RemoveEventListener<WeaponEnum>("AddWeapon", OnAddWeapon);
    }
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Alpha1))
        {
            OnToggleWeapon(1);
        }
        else if (Input.GetKeyDown(KeyCode.Alpha2))
        {
            OnToggleWeapon(2);
        }
        else if (Input.GetKeyDown(KeyCode.Alpha3))
        {
            OnToggleWeapon(3);
        }
        else if(Input.GetKeyDown (KeyCode.Alpha4))
        {
            OnToggleWeapon(4);
        }
        else if (Input.GetKeyDown(KeyCode.Alpha5))
        {
            OnToggleWeapon(5);
        }
        else if (Input.GetKeyDown(KeyCode.Alpha6))
        {
            OnToggleWeapon(6);
        }

        if (Input.GetMouseButtonDown(0))
        {
            isMouseDown = true;
        }
        if(Input.GetMouseButtonUp(0))
        {
            isMouseDown =false;
        }
        if(isMouseDown)
        {
            weaponList[currentIndex - 1].OnAttack(transform.right);
        }
    }
    public void Follow(Vector3 mousePos)
    {
        mousePos.z = 0;
        Vector2 dir = (mousePos - transform.position).normalized;
        transform.right = dir;
        if (mousePos.x < transform.position.x)
        {
            transform.localScale = new Vector3(-1, -1, 1);
        }
        else
        {
            transform.localScale = Vector3.one;
        }
    }
    //却换武器
    private void OnToggleWeapon(int i)
    {
        if (i > weaponList.Count) return;  

        for (int j = 0; j < weaponList.Count; j++)
        {
            if (i-1!= j) 
            {
                weaponList[j].gameObject.SetActive(false);
            }
            else
            {
                currentIndex = i;
                weaponList[j].gameObject.SetActive(true);
            }
        }
        
    }
    //初始化武器
    private void Init()
    {
        List<WeaponEnum> list = PlayerDataSingle.Intacne.WeaponList;

        foreach (var item in list)
        {
            OnAddWeapon(item);
        }
        OnToggleWeapon(currentIndex);
    }
}
